package cn.sciento.core.jackson.serializer;

import cn.sciento.core.jackson.annotation.IgnoreTimeZone;
import cn.sciento.core.oauth.CustomUserDetails;
import cn.sciento.core.oauth.DetailsHelper;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateSerializer extends JsonSerializer<Date> implements ContextualSerializer {
    private boolean ignoreTimeZone = false;

    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (this.ignoreTimeZone) {
            jsonGenerator.writeString(dateFormatGmt.format(date));
        } else {
            CustomUserDetails details = DetailsHelper.getUserDetails();
            if (details != null && details.getTimeZone() != null)
                dateFormatGmt.setTimeZone(TimeZone.getTimeZone(details.getTimeZone()));
            jsonGenerator.writeString(dateFormatGmt.format(date));
        }
    }

    private DateSerializer setIgnoreTimeZone(boolean ignoreTimeZone) {
        this.ignoreTimeZone = ignoreTimeZone;
        return this;
    }

    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        return (new DateSerializer()).setIgnoreTimeZone((property != null && property.getMember().hasAnnotation(IgnoreTimeZone.class)));
    }
}
